'use strict';

const { rejects } = require("assert");

const fs = require('fs');
const { resolve } = require("path");
const path = require('path');
const file = require('../model/file');
module.exports = app => {
  class Controller extends app.Controller {
    async upload() {
      const { ctx, app, service } = this;
      const currentUser = ctx.authUser;
      console.log(ctx.request.files);
      if (!ctx.request.files) {
        return ctx.apiFail('请先选择上传文件');
      }
      ctx.validate({
        file_id: {
          required: true,
          type: 'int',
          defaValue: 0,
          desc: '目录id'
        }
      })
      const file_id = ctx.query.file_id
      console.log('file_id' + file_id);
      console.log(service.file);
      //目录id是否存在
      if (file_id > 0) {
        await service.file.isDirExist(file_id);
      }
      const file = ctx.request.files[0]
      const name = 'egg-oss-demo/' + ctx.genID(10) + path.extname(file.filename)
      //判断用户网盘内容是否不足
      let s = await (new Promise((resolve, rejectect) => {
        fs.stat(file.filepath, (err, stats) => {
          resolve((stats.size / 1024).toFixed(1));
        })
      }))
      console.log(s);
      //上传oss
      if ((currentUser.total_size - currentUser.used_size) < s) {
        return ctx.apiFail('你的可用内存不足')
      }
      let result
      try {
        result = await ctx.oss.put(name, file.filepath)
      } catch (err) {
        console.log(err);
      }
      console.log(result.url);
      //数据写入
      if (result) {
        let addDate = {
          name: file.filename,
          ext: file.mimeType,
          md: result.name,
          file_id,
          user_id: currentUser.id,
          size: parseInt(s),
          isdir: 0,
          url: result.url
        }
        let res = await app.model.File.create(addDate)
        currentUser.used_size = currentUser.used_size + parseInt(s)
        console.log(currentUser);
        currentUser.save()
        return ctx.apiSuccess(res)
      }
      ctx.apiFail('上传失败')
    }


    async list() {
      const { ctx, app } = this
      console.log(ctx.authUser);

      const user_id = ctx.authUser.id

      ctx.validate({
        file_id: {
          required: true,
          type: "int",
          defValue: 0,
          desc: "目录id"
        },
        orderby: {
          required: false,
          type: "string",
          defValue: "name",
          range: {
            in: ['name', 'created_time']
          },
          desc: "排序"
        },
        type: {
          required: false,
          type: "string",
          desc: "类型"
        },
        isdir: {
          required: false,
          type: "int",
          defValue: 2,
          range: {
            in: [0, 1, 2]
          },
          desc: "是否为目录"
        }
      })

      const { file_id, orderby, type, isdir } = ctx.query

      let where = {
        user_id,
        file_id
      }

      if (type && type !== 'all') {
        const Op = app.Sequelize.Op;
        where.ext = {
          [Op.like]: type + '%',
        }
      }

      if (isdir != 2) {
        where.isdir = isdir
      }

      let rows = await app.model.File.findAll({
        where,
        order: [
          ['isdir', 'desc'],
          [orderby, 'desc'],
        ]
      })

      ctx.apiSuccess(rows)
    }

    async createdir() {
      const { ctx, service } = this
      const user_id = ctx.authUser.id

      ctx.validate({
        file_id: {
          required: true,
          type: "int",
          defValue: 0,
          desc: "目录id"
        },
        name: {
          required: false,
          type: "string",
          desc: "文件夹名称"
        }
      })
      let { file_id, name } = ctx.request.body
      if (file_id) {
        await service.file.isDirExist(file_id)
      }
      let res = await app.model.File.create({
        name,
        file_id,
        user_id,
        isdir: 1,
        size: 0
      })
      ctx.apiSuccess(res)


    }

    async rename() {
      const { ctx, app, service } = this
      console.log(ctx.authUser);
      const user_id = ctx.authUser.id
      ctx.validate({
        id: {
          required: true,
          type: "int",
          desc: "文件id"
        },
        name: {
          required: true,
          type: "string",
          desc: "文件夹新名称"
        },
      })
      let { id, name } = ctx.request.body
      // 验证文件是否存在
      let f = await service.file.isExist(id)
      f.name = name
      let res = await f.save()
      ctx.apiSuccess(res)
    }

    async delete() {
      const { ctx, app, service } = this
      const user_id = ctx.authUser.id
      ctx.validate({
        ids: {
          required: true,
          type: "string",
          desc: "删除文件id"
        },
      })
      let { ids } = ctx.request.body
      ids = ids.split(',')
      // 计算文件大小
      let size = 0
      // 存储删除名字
      let dfilename = []
      //查询目录所有
      let files = await app.model.File.findAll({
        where: {
          id: ids,
          user_id
        }
      })
      //查询子目录所有
      let filess = await app.model.File.findAll({
        where: {
          file_id: ids,
          user_id
        }
      })

      files.forEach(item => {
        dfilename.push(item.md)
        size = size + item.size
      });
      filess.forEach(item => {
        if (item.file_id != 0) {
          dfilename.push(item.md)
          size = size + item.size
        }
      });
      //数据库
      let res = await app.model.File.destroy({
        where: {
          id: ids,
          user_id
        }
      })
      //oss
      try {
        // 填写需要删除的多个Object完整路径并设置返回模式为详细模式。Object完整路径中不能包含Bucket名称。
        let result = await ctx.oss.deleteMulti(dfilename);
        //console.log(result);
        // 填写需要删除的多个Object完整路径并设置返回模式为简单模式。Object完整路径中不能包含Bucket名称。
        // let result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt'], {quiet: true});
        console.log(result);
      } catch (e) {
        console.log(e);
      }
      //账户扩容
      if (res) {
        // 减去使用的内存
        size = ctx.authUser.used_size - size
        ctx.authUser.used_size = size > 0 ? size : 0
        ctx.authUser.save()
      }
      ctx.apiSuccess(res)
    }



    async search() {
      const { ctx, app } = this;
      const user_id = ctx.authUser.id;

      ctx.validate({
        keyword: {
          required: true,
          type: "string",
          desc: "关键字"
        },
      })

      let { keyword } = ctx.query

      const Op = app.Sequelize.Op
      console.log(keyword);
      let rows = await app.model.File.findAll({
        where: {
          name: {
            [Op.like]: `%${keyword}%`
          },
          isdir: 0,
          user_id
        }
      })

      ctx.apiSuccess({
        rows
      })
    }


  }
  return Controller;
};
